﻿using RabbitMQ.Client;
using RabbitMQ.Client.Content;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MessageQuque.Common;

namespace MessageQuque
{
    public abstract class EnqueueBase
    {
        // 使用ConnectionFactory创建连接
        private static ConnectionFactory cf = new ConnectionFactory();

        static EnqueueBase()
        {
            // 使用前文的配置环境信息
            cf.UserName = Config.UserName;
            cf.Password = Config.Password;
            cf.VirtualHost = Config.VirtualHost;
            cf.RequestedHeartbeat = 0;
            cf.Endpoint = new AmqpTcpEndpoint(new Uri(Config.UriAddress));
        }

        /// <summary>
        /// 入队
        /// </summary>
        /// <param name="header">头部</param>
        /// <param name="queueName">队列名称</param>
        /// <param name="body">内容</param>
        protected virtual void Enqueue(string header, string queueName, object body)
        {
            using (IConnection conn = cf.CreateConnection())
            {
                using (IModel ch = conn.CreateModel())
                {
                    ch.QueueDeclare(queueName, true, false, false, null);
                    // 构造消息实体对象并发布到消息队列上
                    IMapMessageBuilder b = new MapMessageBuilder(ch);
                    IDictionary<string, object> target = b.Headers;
                    target["header"] = header;
                    IDictionary<string, object> targetBody = b.Body;
                    targetBody["body"] = body.ToJsonSerialize();
                    if (Config.PersistMode)
                    {
                        ((IBasicProperties)b.GetContentHeader()).DeliveryMode = 2;
                    }
                    // 简单发布方式
                    ch.BasicPublish("", queueName, (IBasicProperties)b.GetContentHeader(), b.GetContentBody());
                }
            }
        }
    }
}
